#!/bin/python3
# -*- coding:utf-8 -*-
"""
    [模块名]
    Add By :陈狍子 e4ting@qq.com 2024-07-19 17:17:38
"""
import sys,os

from e4ting import util,log
import yaml

class ConfigParse(metaclass=util.Single):
    default_conf = os.path.join(os.path.dirname(__file__), "../etc/saas.yaml")
    def __init__(self, yaml_path=""):
        self.yaml_path = yaml_path or self.default_conf
        self.load()

    def load(self):
        if not os.path.exists(self.yaml_path):
            log.warn(f"警告: {self.yaml_path} 文件不存在")
            return

        with open(self.yaml_path, 'r', encoding='utf-8') as f:
            self.content = yaml.load(f, Loader=yaml.Loader)

    def get_section(self, section):
        return self.content.get(section, {})

    def __getitem__(self, key):
        return self.get_section(key)

    def get_value(self, section, key):
        return self.content.get(section, {}).get(key, None)

    def keys(self):
        return list(self.content.keys())

    def __repr__(self):
        return "yaml({self.yaml_path}) {keys}".format(self=self, keys=self.keys())

class ConfValue():
    __tag__ = "database"
    def __init__(self, env, config_name, default):
        self.value = default
        # 优先读环境变量
        if env in os.environ:
            self.value = os.environ.get(env)
        elif env.lower() in os.environ:
            self.value = os.environ.get(env.lower())
        # 再读配置文件
        elif config_name in ConfigParse()[self.__tag__]:
            self.value = ConfigParse()[self.__tag__][config_name]

    def __get__(self, instance, owner):
        return self.value
